package com.hs.telepass.utils.security;

import android.content.Context;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

import Decoder.BASE64Decoder;


public class RSA {

    public static final String ALGORITHM = "RSA";
    public static final String ENCODING = "UTF8";



    public static PrivateKey getPrivateKey(Context context, String _path) {
        final String path = _path;
        URL url;
        try {
            InputStream inputStream = context.getAssets().open(path);
//            url = new File(path).toURI().toURL();
            byte[] keyBytes = InputStreamUtils.InputStreamTOByte(inputStream);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
            return kf.generatePrivate(spec);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }



    public static String decrypt(String _encryptedData, PrivateKey _privateKey) throws Throwable {
        final String encryptedData = _encryptedData;
        final PrivateKey privateKey = _privateKey;
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte [] cipherText = cipher.doFinal(new BASE64Decoder().decodeBuffer(encryptedData));
        return new String(cipherText);
    }

    public static byte[] getKeyBytes(URL url) throws URISyntaxException, FileNotFoundException, IOException {
        File f = new File(url.toURI());
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        return keyBytes;
    }

}